package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.FigureEvent;
import cn.stylefeng.guns.modular.business.entity.SubDic;
import cn.stylefeng.guns.modular.business.enums.FigureEventExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.FigureEventMapper;
import cn.stylefeng.guns.modular.business.pojo.FigureEventRequest;
import cn.stylefeng.guns.modular.business.service.FigureEventService;
import cn.stylefeng.guns.modular.business.service.SubFileInfoService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 人物相关事件表业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/25 16:46
 */
@Service
public class FigureEventServiceImpl extends ServiceImpl<FigureEventMapper, FigureEvent> implements FigureEventService {

    @Resource
    private SubFileInfoService subFileInfoService;
    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;

	@Override
    public void add(FigureEventRequest figureEventRequest) {
        FigureEvent figureEvent = new FigureEvent();
        BeanUtil.copyProperties(figureEventRequest, figureEvent);
        this.save(figureEvent);
    }

    @Override
    public void del(FigureEventRequest figureEventRequest) {
        FigureEvent figureEvent = this.queryFigureEvent(figureEventRequest);
        this.removeById(figureEvent.getId());
    }

    @Override
    public void edit(FigureEventRequest figureEventRequest) {
        FigureEvent figureEvent = this.queryFigureEvent(figureEventRequest);
        BeanUtil.copyProperties(figureEventRequest, figureEvent);
        this.updateById(figureEvent);
    }

    @Override
    public FigureEvent detail(FigureEventRequest figureEventRequest) {
        return this.queryFigureEvent(figureEventRequest);
    }


    @Override
    public List<FigureEvent> findList(FigureEventRequest figureEventRequest) {
        LambdaQueryWrapper<FigureEvent> wrapper = this.createWrapper(figureEventRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/25 16:46
     */
    private FigureEvent queryFigureEvent(FigureEventRequest figureEventRequest) {
        FigureEvent figureEvent = this.getById(figureEventRequest.getId());
        if (ObjectUtil.isEmpty(figureEvent)) {
            throw new ServiceException(FigureEventExceptionEnum.FIGUREEVENT_NOT_EXISTED);
        }
        return figureEvent;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/25 16:46
     */
    private LambdaQueryWrapper<FigureEvent> createWrapper(FigureEventRequest figureEventRequest) {
        LambdaQueryWrapper<FigureEvent> queryWrapper = new LambdaQueryWrapper<>();

        Long id = figureEventRequest.getId();
        String figureName = figureEventRequest.getFigureName();
        String figureChronicle = figureEventRequest.getFigureChronicle();
        String historicalChronicle = figureEventRequest.getHistoricalChronicle();
        String adChronicle = figureEventRequest.getAdChronicle();
        String figureIntroduction = figureEventRequest.getFigureIntroduction();
        String figureAnnotation = figureEventRequest.getFigureAnnotation();
        String historyPeriod = figureEventRequest.getHistoryPeriod();
        String figureLaiyuanzhishu = figureEventRequest.getFigureLaiyuanzhishu();
        Long figureZhishupage = figureEventRequest.getFigureZhishupage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), FigureEvent::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureName), FigureEvent::getFigureName, figureName);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureChronicle), FigureEvent::getFigureChronicle, figureChronicle);
        queryWrapper.like(ObjectUtil.isNotEmpty(historicalChronicle), FigureEvent::getHistoricalChronicle, historicalChronicle);
        queryWrapper.like(ObjectUtil.isNotEmpty(adChronicle), FigureEvent::getAdChronicle, adChronicle);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureIntroduction), FigureEvent::getFigureIntroduction, figureIntroduction);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureAnnotation), FigureEvent::getFigureAnnotation, figureAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyPeriod), FigureEvent::getHistoryPeriod, historyPeriod);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureLaiyuanzhishu), FigureEvent::getFigureLaiyuanzhishu, figureLaiyuanzhishu);
        queryWrapper.eq(ObjectUtil.isNotNull(figureZhishupage), FigureEvent::getFigureZhishupage, figureZhishupage);

        return queryWrapper;
    }

    @Override
    public PageResult<Map<String,Object>> findPage(FigureEventRequest figureEventRequest) {
        LambdaQueryWrapper<FigureEvent> queryWrapper = new LambdaQueryWrapper<>();
        String figureName = figureEventRequest.getFigureName();
        queryWrapper.eq(ObjectUtil.isNotEmpty(figureName), FigureEvent::getFigureName, figureName);

        Page<FigureEvent> sysRolePage = this.page(PageFactory.defaultPage(), queryWrapper);

        PageResult<FigureEvent> figureEventPageResult = PageResultFactory.createPageResult(sysRolePage);
        PageResult<Map<String,Object>> pageResult = new PageResult<>();
        List<FigureEvent> figureEventList = figureEventPageResult.getRows();
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(FigureEvent figureEvent:figureEventList){
            Map<String, Object> map = new HashMap<String, Object>();
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.RWSJ+figureEvent.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
//            String hdeve = StrUtil.sub(figureEvent.getFigureIntroduction(),0,20);
            map.put("title",figureEvent.getFigureTitle());
            map.put("rhdAnnalsfrom",figureEvent.getFigureLaiyuanzhishu());
            mapList.add(map);

        }
        pageResult.setRows(mapList);
        pageResult.setPageSize(figureEventPageResult.getPageSize());
        pageResult.setPageNo(figureEventPageResult.getPageNo());
        pageResult.setTotalPage(figureEventPageResult.getTotalPage());
        pageResult.setTotalRows(figureEventPageResult.getTotalRows());
        return pageResult;
    }

    @Override
    public List<Map<String,Object>> findAllList(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<FigureEvent> wrapper = createWrapperByTown(riverList,townList,times,name);
        List<FigureEvent>  list = this.list(wrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(FigureEvent figureEvent:list) {
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("title", figureEvent.getFigureName());
            map.put("historyDating",figureEvent.getHistoricalChronicle());
            map.put("theCommon",figureEvent.getAdChronicle());
            map.put("from",figureEvent.getFigureLaiyuanzhishu() );
            map.put("createTime", DateUtil.format(figureEvent.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",YunHeKey.RWSJ);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.RWSJ+figureEvent.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<FigureEvent> createWrapperByTown(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<FigureEvent> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(name), FigureEvent::getFigureName, name).or()
                .like(ObjectUtil.isNotNull(name), FigureEvent::getHistoricalChronicle, name).or()
                .like(ObjectUtil.isNotNull(name), FigureEvent::getAdChronicle, name).or()
                .like(ObjectUtil.isNotNull(name), FigureEvent::getFigureLaiyuanzhishu, name).or());
        if( !riverList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < riverList.size(); i++) {
                    String dicAname = riverList.get(i).getDicAname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicAname), FigureEvent::getXgRiver, dicAname);
                    if (i != riverList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( !townList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < townList.size(); i++) {
                    String dicZname = townList.get(i).getDicZname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicZname), FigureEvent::getXgTown, dicZname);
                    if (i != townList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( times.length !=0) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < times.length; i++) {
                    String time = times[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), FigureEvent::getHistoryPeriod, time);
                    if (i != times.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper;
    }

    @Override
    public Map<String, Object> toReview(String jmId) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmId, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.RWSJ,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {
            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(FigureEventExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<FigureEvent> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            Map<String, Object> map = new HashMap<>();
            return map;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), FigureEvent::getId, id);
        List<FigureEvent> FigureEventList = this.list(queryWrapper);

        Map<String ,Object> objectMap = new HashMap<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (FigureEvent figureEvent : FigureEventList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(figureEvent), Map.class);

            // 获取类的属性
            Field[] declaredFields = FigureEvent.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {
                String title ="";
                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名
                        if( "figureIntroduction".equals(field.getName()) || "figureTitle".equals(field.getName())  || "figureAnnotation".equals(field.getName())) {
                            if( "figureTitle".equals(field.getName())  ) {
                                p.put("title", map.get(field.getName()));
                            }else
                            if( "figureAnnotation".equals(field.getName())  ) {
                                p.put("annotation", map.get(field.getName()));
                            }
                            else {
                                p.put(field.getName(), map.get(field.getName()));
                            }
                        }else {
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));

                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }

                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.YHRW,mapList.get(0).get("title").toString(),userid,request);
        }
        objectMap.putAll(mapList.get(0));
        return objectMap;
    }

}